package com.hethongviet.preventingmachine;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.helps.SMSHelper;

public final class Utils
{

	private static ProgressDialog _progressDialog = null;

	public static boolean isSdCardPresent()
	{
		return android.os.Environment.getExternalStorageState()
				.equalsIgnoreCase(android.os.Environment.MEDIA_MOUNTED);
	}

	public static boolean isValidNumber(String number)
	{
		for (int index = 0; index < number.length(); index++)
		{
			char c = number.charAt(index);

			if (!Character.isDigit(c))
			{
				Log.d("Utils", "Invalid number!!! ");
				return false;
			}
		}
		Log.d("Utils", "Valid number!!! ");
		return true;
	}

	public boolean isValidMessageChar(char c)
	{
		return Character.isLetterOrDigit(c) || c == ' ' || c == '_' || c == '('
				|| c == ')' || c == '-' || c == SMSHelper.CODE_START
				|| c == SMSHelper.CODE_REPLACE_NULL
				|| c == SMSHelper.CODE_ERROR_UPDATE
				|| c == SMSHelper.CODE_SEPARATE || c == SMSHelper.CODE_END;
	}

	/**
	 * example:
	 * https://www.google.com.vn/search?q=%40&ie=utf-8&oe=utf-8&aq=t&rls=
	 * org.mozilla :en-US:official&client=firefox-a
	 * 
	 * encode: &0 = :
	 */
	private static final char[] WEB_ADDRESS_SPECIAL_CHARS = { ':', '/', '.',
			'?', '=', '+', '-', '%', '&', ' ' };
	private static final char[] WEB_ADDRESS_SPECIAL_CHARS_ENCODE = { '0', '1',
			'2', '3', '4', '5', '6', '7', '8', '9' };
	private static final char WEB_ADDRESS_CHAR_ENCODE = '&';

	public static String encodeWebAddressChar(char c)
	{
		for (int i = 0; i < WEB_ADDRESS_SPECIAL_CHARS.length; i++)
		{
			if (c == WEB_ADDRESS_SPECIAL_CHARS[i])
			{
				return WEB_ADDRESS_CHAR_ENCODE + ""
						+ WEB_ADDRESS_SPECIAL_CHARS_ENCODE[i];
			}
		}
		return "" + c;
	}

	public static boolean isValidWebAddressChar(char c)
	{
		if (!Character.isLetterOrDigit(c))
		{
			for (int i = 0; i < WEB_ADDRESS_SPECIAL_CHARS.length; i++)
			{
				if (c == WEB_ADDRESS_SPECIAL_CHARS[i]) return true;
			}
			return false;
		}
		return true;
	}

	public static String encodeWebAddress(String address)
	{
		String newAdress = "";
		for (int i = 0; i < address.length(); i++)
		{
			newAdress += encodeWebAddressChar(address.charAt(i));
		}
		return newAdress;
	}

	public static String decodeWebAddress(String address)
	{
		String newAdress = "";
		for (int i = 0; i < address.length(); i++)
		{
			char c = address.charAt(i);
			if (c != WEB_ADDRESS_CHAR_ENCODE) newAdress += c;
			else
			{
				try
				{
					int indexChar = Integer.parseInt("" + address.charAt(++i));
					newAdress += WEB_ADDRESS_SPECIAL_CHARS[indexChar];
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		return newAdress;
	}

	/**
	 * Get valid message content
	 * 
	 * @param origin
	 *            message
	 * @return message content
	 */
	public static String prepareMessage(String message)
	{
		if (message == null) return null;
		String messageAfter = null;
		boolean isRead = false;
		int index = 0;

		for (index = 0; index < message.length(); index++)
		{
			char c = message.charAt(index);

			if (!Character.isLetterOrDigit(c) && c != ' ' && c != '_'
					&& c != '(' && c != ')' && c != '-'
					&& c != SMSHelper.CODE_START
					&& c != SMSHelper.CODE_REPLACE_NULL
					&& c != SMSHelper.CODE_ERROR_UPDATE
					&& c != SMSHelper.CODE_SEPARATE && c != SMSHelper.CODE_END)
			{
				continue;
			}

			if (c == SMSHelper.CODE_START)
			{
				isRead = true;
				messageAfter = "" + c;
			}
			else if (c == SMSHelper.CODE_START)
			{
				messageAfter += c;
				break;
			}
			else if (!isRead)
			{
				continue;
			}
			else
				messageAfter += c;
		}

		if (index + Constants.MAX_ID_LENGTH <= message.length())
		{
			for (int indexId = 0; indexId < Constants.MAX_ID_LENGTH; indexId++)
			{
				messageAfter += message.charAt(index + indexId);
			}
		}

		return messageAfter;
	}

	public static void prepareWindow(Activity activity)
	{
		if (Config.IS_FULL_SCREEN) // making full screen
		{
			activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
			activity.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
		else if (Config.IS_SHOW_CLIENT_NAME)// show client name
		{
			// if (activity instanceof JobTrackingActivity
			// || activity instanceof AboutActivityLeft
			// || activity instanceof AboutActivityRight)
			// {
			// activity.setTitle(activity.getString(R.string.textAppNameComon));
			// }
			// else
			{
				// activity.setTitle(_user.getCompanyName());
			}
		}
		else
			activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	public static void debug(String string)
	{
		if (Config.IS_DEBUG) Log
				.d("Debug", "@@@@@@@@@@@@@@@@@@@@@@@ " + string);
	}

	public static void toast(Activity activity, int stringId)
	{
		if (Config.IS_DEBUG && Config.IS_DEBUG_SHOW_SMS_SENDING)
		{
			Toast.makeText(activity.getBaseContext(), stringId,
					Toast.LENGTH_SHORT).show();
		}
	}

	public static void toast(Activity activity, String string)
	{
		if (Config.IS_DEBUG && Config.IS_DEBUG_SHOW_SMS_SENDING)
		{
			Toast.makeText(activity.getBaseContext(), string,
					Toast.LENGTH_SHORT).show();
		}
	}

	public static void showProgress(Activity activity)
	{
		debug("Call Show Progress Dialog!!!!!!!!");
		try
		{
			_progressDialog = ProgressDialog.show(activity, "",
					activity.getString(R.string.please_wait), true, false);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static boolean isContextRunning(Activity activity,
			String packagePathContext)
	{

		ActivityManager activityManager = (ActivityManager) activity
				.getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);

		List<RunningTaskInfo> services = activityManager
				.getRunningTasks(Integer.MAX_VALUE);

		for (RunningTaskInfo runningTaskInfo : services)
		{
			if (runningTaskInfo.topActivity.toString().contains(
					packagePathContext)) return true;
		}
		return false;
	}

	public static void hideProgressDialog()
	{
		debug("Call hide Progress Dialog!!!!!!!!");
		try
		{
			if (_progressDialog != null)
			{
				_progressDialog.hide();
				_progressDialog.dismiss();
				_progressDialog = null;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void callOnWindowFocusChange(Activity activity)
	{
		debug("Call onWindowFocusChange!!!!!!!!");
		activity.onWindowFocusChanged(true);
	}

	public static boolean isStringNull(String string)
	{
		return string == null || string.equals("");
	}
}
